package com.ed.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ed.constant.AIConstant;
import com.ed.context.UserContext;
import com.ed.domain.ChatConversation;
import com.ed.domain.ChatMessage;
import com.ed.domain.Response;
import com.ed.mapper.IChatConversationMapper;
import com.ed.mapper.IChatMessageMapper;
import com.ed.mapper.IResponseMapper;
import com.ed.service.IAIService;
import com.ed.service.ResponseService;
import com.ed.task.AITask;
import com.ed.vo.AIAnalysisVO;
import com.ed.vo.ResponseQAVo;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class AIServiceImpl implements IAIService {
	@Autowired
	private IResponseMapper responseMapper;
	@Autowired
	private ResponseService responseService;
	@Autowired
	private IChatConversationMapper chatConversationMapper;
	@Autowired
	private IChatMessageMapper chatMessageMapper;
	@Autowired
	private ChatClient chatClient;
	@Autowired
	private AITask aiTask;
	
	/**
	 * 获取用户答题结果
	 *
	 * @return
	 */
	@Override
	public AIAnalysisVO getResponse() {
		Integer userId = 3;
		AIAnalysisVO aiAnalysisVO = new AIAnalysisVO();
		QueryWrapper<Response> faqQueryWrapper = new QueryWrapper<>();
		faqQueryWrapper
			.eq("user_id", userId)
			.eq("type", "faq")
			.orderByDesc("submit_time")
			.last("limit 1");
		// 1.查询用户的答题结果
		//faq
		List<Response> faqResponses = responseMapper.selectList(faqQueryWrapper);
		if (faqResponses != null && !faqResponses.isEmpty()) {
			Response faqResponse = faqResponses.get(0);
			List<ResponseQAVo> faqResponseQAVos = responseService.detailsByResponse(faqResponse);
			for (ResponseQAVo faqResponseQAVo : faqResponseQAVos) {
				if (faqResponseQAVo.getAnswer() == null) {
					faqResponseQAVo.setAnswer("未作答");
					faqResponseQAVo.setChoice(-1);
				}
			}
			aiAnalysisVO.setFaqScore(faqResponse.getScore());
			aiAnalysisVO.setFaqDesc("社会活动调查问卷");
			aiAnalysisVO.setFaqList(faqResponseQAVos);
		}
		
		
		//hama
		QueryWrapper<Response> hamaQueryWrapper = new QueryWrapper<>();
		hamaQueryWrapper
			.eq("user_id", userId)
			.eq("type", "hama")
			.orderByDesc("submit_time")
			.last("limit 1");
		List<Response> hamaResponses = responseMapper.selectList(hamaQueryWrapper);
		if (hamaResponses != null && !hamaResponses.isEmpty()) {
			Response hamaResponse = hamaResponses.get(0);
			List<ResponseQAVo> hamaResponseQAVos = responseService.detailsByResponse(hamaResponse);
			for (ResponseQAVo hamaResponseQAVo : hamaResponseQAVos) {
				if (hamaResponseQAVo.getAnswer() == null) {
					hamaResponseQAVo.setAnswer("未作答");
					hamaResponseQAVo.setChoice(-1);
				}
			}
			aiAnalysisVO.setHamaScore(hamaResponse.getScore());
			aiAnalysisVO.setHamaDesc("哈密尔顿焦虑量表");
			aiAnalysisVO.setHamaList(hamaResponseQAVos);
		}
		return aiAnalysisVO;
	}
	
	@Override
	public boolean addChat(ChatConversation chatConversation) {
		//填充字段
		chatConversation.setConversationId(UUID.randomUUID().toString() + UserContext.getCurrentUser());
		chatConversation.setIsDeleted((byte)0);
		chatConversation.setCreateTime(LocalDateTime.now());
		chatConversation.setUpdateTime(LocalDateTime.now());
		chatConversation.setUserId(UserContext.getCurrentUser());
		int insert = chatConversationMapper.insert(chatConversation);
		return insert > 0;
	}
	
	@Override
	@Transactional
	public void delChat(ChatConversation chatConversation) {
		//先根据id删除会话消息
		String conversationId = chatConversation.getConversationId();
		QueryWrapper<ChatMessage> messageWrapper = new QueryWrapper<>();
		messageWrapper.eq("conversation_id", conversationId);
		int rows = chatMessageMapper.delete(messageWrapper);
		//再删除会话
		QueryWrapper<ChatConversation> conversationQueryWrapper = new QueryWrapper<>();
		conversationQueryWrapper.eq("conversation_id", conversationId);
		int delete = chatConversationMapper.delete(conversationQueryWrapper);
	}
	
	@Override
	public List<ChatConversation> listChats() {
		QueryWrapper<ChatConversation> wrapper = new QueryWrapper<>();
		wrapper.eq("user_id", UserContext.getCurrentUser());
		List<ChatConversation> chatConversations = chatConversationMapper.selectList(wrapper);
		return chatConversations;
	}
	
	@Override
	@Transactional
	public String chat(ChatMessage chatMessage) {
		//1.保存用户的会话id
		chatMessage.setMessageType("text");
		chatMessage.setRole("user");
		chatMessage.setCreateTime(LocalDateTime.now());
		chatMessageMapper.insert(chatMessage);
		//获取这个对话的id，便于后续使用
		Integer id = chatMessage.getId();
		//1.2更新会话时间
		QueryWrapper<ChatConversation> conversationQueryWrapper = new QueryWrapper<>();
		conversationQueryWrapper.eq("conversation_id", chatMessage.getConversationId());
		ChatConversation chatConversation = new ChatConversation();
		chatConversation.setUpdateTime(LocalDateTime.now());
		chatConversationMapper.update(chatConversation, conversationQueryWrapper);
		//2.客户端发送(通过advisor直接发送，利用框架保证上下文对话)
		String aiReply = chatClient.prompt()
			.advisors(advisor ->
				// 动态设置当前会话 ID（从 chatMessage 中获取）
				advisor.param(AIConstant.ID_KEY, chatMessage.getConversationId())
			)
			.user(chatMessage.getContent()) // 用户输入
			.call()
			.content();
		//3.写入对话记录（异步）
		//填充系统对话
		ChatMessage assistantMessage = new ChatMessage();
		assistantMessage.setCreateTime(LocalDateTime.now());
		assistantMessage.setConversationId(chatMessage.getConversationId());
		assistantMessage.setContent(aiReply);
		assistantMessage.setRole("assistant");
		assistantMessage.setMessageType("text");
		assistantMessage.setReplyId(id);
		aiTask.recordChat(assistantMessage);

		return aiReply;
	}
	
	@Override
	public List<ChatMessage> listChatHistory(String conversationId) {
		QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("conversation_id", conversationId);
		queryWrapper.orderByAsc("create_time");
		List<ChatMessage> chatMessages = chatMessageMapper.selectList(queryWrapper);
		return chatMessages;
	}
}
		
		



